﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

namespace dev.queensland.web.webservices
{
    [Serializable]
    public class Message
    {
        public string Content { get; set; }

        public Message()
        {

        }
        public Message(string content)
        {
            this.Content = content;
        }
    }

    [Serializable]
    public class XFile
    {
        public byte[] FileBytes { get; set; }
        public string FileName { get; set; }
    }

    /// <summary>
    /// Summary description for EchoWebService
    /// </summary>
    [WebService(Namespace = "http://dev.queensland.web/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class EchoWebService : System.Web.Services.WebService
    {
        Microsoft.AspNet.SignalR.Client.HubConnection hubConnection = null;
        Microsoft.AspNet.SignalR.Client.IHubProxy chatHubProxy = null;

        public EchoWebService()
        {
            hubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection("http://localhost:80");
            chatHubProxy = hubConnection.CreateHubProxy("chatHub");
            hubConnection.Start();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
        public string HelloWorld()
        {
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            #region comment out
            //HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "http://dev.3danalect.web");
            //HttpContext.Current.Response.Headers.Clear();
            //HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            //HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "http://dev.3danalect.web/");
            //HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            //HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            //HttpContext.Current.Response.Headers.Add("Access-Control-Max-Age", "1728000");
            //Context.Response.Headers.Add("Access-Control-Allow-Origin", "http://dev.3danalect.web");
            //Context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            //Context.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            //Context.Response.Headers.Add("Access-Control-Max-Age", "1728000");
            #endregion comment out

            System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            string message = "Hello World " + DateTime.Now.ToString();

            return javaScriptSerializer.Serialize(new Message(message));

        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
        public Message Echo(string message)
        {
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            
            System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            string message1 = "Hello World " + message + DateTime.Now.ToString();

            //return javaScriptSerializer.Serialize(new Message(message1));
            return new Message(message1);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
        public XFile Download(string message)
        {
            //System.IO.FileStream dd = System.IO.File.OpenRead(Server.MapPath("~/pdfs/Flux-deck.pdf"));
            //byte[] Bytes = new byte[dd.Length];
            //dd.Read(Bytes, 0, Bytes.Length);


            System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("~/pdfs/Flux-deck.pdf"));
            System.IO.FileStream fs = fi.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] fileBytes = new byte[fs.Length];
            fs.Read(fileBytes, 0, fileBytes.Length);

            //Context.Response.Clear();
            //Context.Response.ContentType = "application/octet-stream";
            //Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + "Flux-deck.pdf" + "\"");
            //Context.Response.OutputStream.Write(fileBytes, 0, fileBytes.Count());

            return new XFile
            {
                FileName = fi.Name,
                FileBytes = fileBytes
            };

            //Context.Response.Clear();
            //Context.Response.ClearHeaders();
            //string contentType = System.Web.MimeMapping.GetMimeMapping(fi.Name);
            ////Context.Response.ContentType = file.ContentType;
            //Context.Response.ContentType = contentType;
            //Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fi.Name + "\"");
            ////Context.Response.AddHeader("Content-Length", file.FileSize.ToString());
            //Context.Response.AddHeader("Content-Length", fileBytes.Length.ToString());
            //Context.Response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
            //Context.Response.Flush();
            //Context.Response.End();

            //Context.Response.TransmitFile(Server.MapPath("~/pdfs/Flux-deck.pdf"));

            // https://support.microsoft.com/en-us/kb/318425
            // https://msdn.microsoft.com/en-us/library/aa528822.aspx
            // http://stackoverflow.com/questions/2239623/download-file-from-webservice-in-asp-net-site
        }


        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
        public void Notify(string moduleType, string title, string message)
        {
            //Context.Response.Clear();
            //Context.Response.ContentType = "application/json";
            //Context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            //System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            //string message1 = "Hello World " + message + DateTime.Now.ToString();

            ////return javaScriptSerializer.Serialize(new Message(message1));
            //return new Message(message1);


            //return hubConnection.State.ToString();
            //hubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection("http://localhost:80");
            //chatHubProxy = hubConnection.CreateHubProxy("chatHub");
            ////await hubConnection.Start();
            ////await chatHubProxy.Invoke("Send", "mytitle", "mymessage");


            ////Start connection
            //hubConnection.Start().ContinueWith(task =>
            //{
            //    if (task.IsFaulted)
            //    {
            //        Console.WriteLine("Failed to start: {0}", task.Exception.GetBaseException());
            //    }
            //    else
            //    {
            //        Console.WriteLine("Success! Connected with client connection id {0}", hubConnection.ConnectionId);
            //        chatHubProxy.Invoke("Send", "mytitle", "mymessage");
            //        //myHub.Invoke("Send", "lol");
            //    }
            //});

            //SignalR.ChatHub hub = new SignalR.ChatHub();
            //hub.Send("my username", "my cutomse messag");

            //Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetConnectionContext<SignalR.ChatHub>();

            ////////////////////////////////////////////////////////////////

            // Working sample code;
            // Assumes hub is on the same server as this code
            var hubContext = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<SignalR.ChatHub>();
            hubContext.Clients.All.broadcastMessage("send name", "my send message");
            hubContext.Clients.All.Send("send name", "my send message");

            ////////////////////////////////////////////////////////////////

            // Working sample code
            // Assumes that hub is on the specified url
            hubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection("http://localhost:80");
            chatHubProxy = hubConnection.CreateHubProxy("chatHub");
            hubConnection.Start().Wait();
            chatHubProxy.Invoke("Send", "myname", "mymessage");


        }
    }
}
